package com.cheyun.netsalev3.view

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.RelativeLayout
import android.widget.Toast
import androidx.annotation.NonNull
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.CustomerEditTagAdapter
import com.cheyun.netsalev3.adapter.MyAdapter
import com.cheyun.netsalev3.bean.*
import com.cheyun.netsalev3.bean.records.Follow
import com.cheyun.netsalev3.databinding.ActivityAddClueBinding
import com.cheyun.netsalev3.databinding.ActivityEditClubBinding
import com.cheyun.netsalev3.utils.*
import com.cheyun.netsalev3.viewmodel.AddClueActivityViewModel
import com.cheyun.netsalev3.widget.SyLinearLayoutManager
import com.dou361.dialogui.DialogUIUtils
import com.dou361.dialogui.listener.DialogUIItemListener
import com.jeremyliao.liveeventbus.LiveEventBus
import com.tencent.qcloud.tim.uikit.component.picture.imageEngine.impl.GlideEngine
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagFlowLayout
import java.io.File

class EditClubActivity : BaseActivity<ActivityAddClueBinding>() {
//ActivityEditClubBinding
    private var ed = EditClueParam()
    private var data = ClueDetails()
    private var activity:Activity? = null
//    var clueDatail:ClueDetails? = null
    override fun initContentView(): Int {
//        return R.layout.activity_edit_club
    return R.layout.activity_add_clue
    }

    override fun initViewModel(): ViewModel? {
        data = intent.getSerializableExtra("data") as ClueDetails
        ed.tid = data.tid.toString()
        ed.uname = data.uname
        ed.phone = data.phone
        ed.sex = data.sex.toString()
        ed.infotype = data.infotype
        ed.infotypename = data.infotypename
        ed.infoplace = data.infoplace
        ed.infoplacename = data.infoplacename
        ed.infosource = data.infosource
        ed.infosourcename = data.infosourcename

        ed.ebrandname = data.brandname
        ed.series = data.series
        ed.eseriesname = data.seriesname
        ed.spec = data.spec
        ed.especname = if(data.specname == null)"" else data.specname
        ed.brandgroup = data.brandgroup

        ed.province = data.province
        ed.provincegroup = data.provincegroup
        ed.cityname = data.region

        ed.pbrand = data.pbrand
        ed.pseries = data.pseries
        ed.address = data.address

        ed.effective = data.effective

        ed.pseriesname = data.pseriesname
        ed.pbrandname = data.pbrandname
//        if(data.secseries.isNotEmpty()) {
//            ed.secssgroup = data.secssgroup + "," + data.secspec
//        }
        ed.secssgroup = data.secssgroup

        ed.customertype = data.customertype

        ed.competitor = TextUtils.join(",",data.competitor)
        ed.competitorname =  TextUtils.join(",",data.competitorname)

        ed.followtime = CommonFunc.getCurrentFullDate()
        //跟进相关不回填
//        ed.followinfo = data.followinfo
//        ed.followstate = data.followstate.toString()
//        ed.followstatename = data.followstatename
//        ed.customerlevel = data.customerlevel.toString()
//        ed.customerlevelname = data.customerlevelname
//        ed.remindetime = data.remindetime
//        ed.connectway = data.connectway
//        ed.connectwayname = data.connectwayname
//        ed.ncwayname = data.
//        ed.ncway = data.ncway

        ed.cityname = data.provincename + " "+ data.cityname
        ed.countyname = data.countyname
        ed.provincegroup = data.provincegroup


        var factory = InjectorUtils.getAddClueActivityViewModelFactory(ed,"",null)
        return ViewModelProviders.of(this, factory).get(AddClueActivityViewModel::class.java)
    }

    var customerEditTagAdapter: CustomerEditTagAdapter? = null
    var customerTagAdapter: CustomerEditTagAdapter? = null
    override fun initView() {
        activity = this
        binding.headView.titleText?.text = "创建跟进"
        binding.radioBut.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.nanBut -> binding.viewModel?.setSex(1)
                R.id.nvBut -> binding.viewModel?.setSex(2)
                R.id.nullBut -> binding.viewModel?.setSex(0)
            }
        }
        binding.cityText.text = ed.cityname
        binding.regionText.text = ed.countyname
        binding.txtXianyouche.text = data.pbrandname + " " + data.pseriesname
        binding.txtShouxuanche.text = data.seriesname + " "+ data.specname
        binding.txtDuibiche.text = ed.competitorname
        binding.txtBeixuanche.text = data.secseries + " "+ data.secspecname

        binding.phoneEdt.isEnabled = false
        binding.viewModel?.editBtnEnable?.observe(this, Observer {
            binding.addBut.isEnabled = it
        })

        customerTagAdapter = CustomerEditTagAdapter(this,null,true)
        binding.userTagFlow.setAdapter(customerTagAdapter)

        customerEditTagAdapter = CustomerEditTagAdapter(this,null ,true)
        binding.customerTagFlow.setAdapter(customerEditTagAdapter)

        binding.customerTagFlow.setOnTagClickListener(object : TagFlowLayout.OnTagClickListener{
            override fun onTagClick(view: View?, position: Int, parent: FlowLayout?): Boolean {
                binding.viewModel?.removeCustomerEditTag(position)
                return true
            }
        })

        binding.userTagFlow.setOnTagClickListener(object : TagFlowLayout.OnTagClickListener{
            override fun onTagClick(view: View?, position: Int, parent: FlowLayout?): Boolean {
                binding.viewModel?.removeUserTag(position)
                return true
            }
        })

        binding.viewModel?.setActivity(this)

//        LiveEventBus.get()
//                .with("uploadOrderImg", String::class.java)
//                .observe(this, Observer {
//                    if (!TextUtils.isEmpty(it)) {
//                        images.add(it)
//                        setImages()
//                    }
//                })
    }

    override fun initData() {
//        var chance = MySharedPreferences.getLoginData()?.member?.apps?.chance
//        if(chance!=null) {
//            if (MySharedPreferences.getLoginData()?.member?.apps?.chance?.contains("9006")!!) {
//                binding.phoneEdt.isEnabled = true
//            }
//        }
//        if(MySharedPreferences.getLoginData()?.member?.isadmin == 1){
//            binding.phoneEdt.isEnabled = true
//        }
        binding.viewModel?.getFollowStatus()
        binding.viewModel?.initTags(data.alllabels)

        if(binding.viewModel?.editClueParam?.sex.equals("1")){
            binding.nanBut.isChecked = true
        }else if(binding.viewModel?.editClueParam?.sex.equals("2")){
            binding.nvBut.isChecked = true
        }else{
            binding.nullBut.isChecked = true
        }

        binding.viewModel?.customerOwnerTag?.observe(this, Observer {
            customerEditTagAdapter?.setData(it)
        })
        binding.viewModel?.userTag?.observe(this, Observer {
            customerTagAdapter?.setData(it)
        })

        binding.viewModel?.editBtnEnable?.observe(this, Observer {
            binding.addBut.isEnabled = it
        })
    }




    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == 102) {
            data?.apply {
                var carBrandParam = getSerializableExtra("car") as CarBrandParam
                if(requestCode == 101){
                    //首选车，意向车
                    binding.viewModel?.setYixiangCarData(carBrandParam)
                    binding.txtShouxuanche.text = carBrandParam.seriesname + " "+ carBrandParam.specname
                }else if(requestCode == 102){
                    //备选车
                    binding.viewModel?.setBeixuanCarData(carBrandParam)
                    binding.txtBeixuanche.text = carBrandParam.seriesname + " "+ carBrandParam.specname
                }else{
                    binding.viewModel?.setCarData(carBrandParam)
//                binding.ebrandname.text = carBrandParam.brandname
//                    binding.eseriesname.text = carBrandParam.seriesname
//                    binding.especname.text = carBrandParam.specname
//                    if(carBrandParam.spec_select > 0){
//                        binding.especxinghao.visibility = View.VISIBLE
//                        binding.viewModel?.editClueParam?.needSpec = true
//                    }else{
//                        binding.especxinghao.visibility = View.GONE
//                        binding.viewModel?.editClueParam?.needSpec = false
//                    }
                }
            }
        }
        if (resultCode == 103) {
            data?.apply {
                var shen = getSerializableExtra("shen") as CarPinPaParam
                var shi = getSerializableExtra("shi") as CarPinPaParam
                var que = getSerializableExtra("que") as CarPinPaParam
                var show = shen.title + " " + shi.title + " " + que.title
                var id = shen.id.toString() + "," + shi.id.toString() + "," + que.id.toString()
                binding.cityText.text = shen.title + " " + shi.title
                binding.regionText.text = que.title
                binding.viewModel?.setCityData(show, id)
            }
        }
        if (resultCode == 104) {
            data?.apply {
                var carBrandParam = getSerializableExtra("car") as CarBrandParam
                binding.viewModel?.setCarData2(carBrandParam)
                binding.txtXianyouche.text = carBrandParam.brandname + " " + carBrandParam.seriesname
            }
        }
        if (resultCode == 105) {
            data?.apply {
                var carBrandParam = getSerializableExtra("car") as CarBrandParam
                binding.viewModel?.addCompetitor(carBrandParam)
                binding.txtDuibiche.text = carBrandParam.brandname + " " + carBrandParam.seriesname
            }
        }
        if(resultCode == 106){
            data?.apply {
//                var ids = getStringExtra("ids")
                var list = getSerializableExtra("list") as ArrayList<DialogParam>
                binding.viewModel?.setUserTag(list)

            }
        }
    }

//    fun changeLayoutHeight(type:Int,count:Int){
//        if(type == 1){
//            var param = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,count*180);
//            binding.competitorRecyclerView.setLayoutParams(param);
//        }
//        if(type == 2){
//            var param = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,count*180);
//            binding.tagRecyclerView.setLayoutParams(param);
//        }
//        if(type == 3){
//            var param = RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,count*180);
//            binding.tagOffRecyclerView.setLayoutParams(param);
//        }
//    }

//    private fun takePhone() {
//        val captureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
//        // 判断是否有相机
//        if (captureIntent.resolveActivity(this.activity!!.getPackageManager()) != null) {
//            var photoUri: Uri? = null
//
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
//                photoUri = FileProvider.getUriForFile(this.activity!!, this.activity!!.getPackageName() + ".provider", fileUri)
//            } else {
//                photoUri = Uri.fromFile(fileUri)
//            }
//            mCameraUri = photoUri
//            if (photoUri != null) {
////                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri)
//                captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
//                startActivityForResult(captureIntent, 1)
//            }
//        }
//    }
//
//    fun pickPhoto() {
//        val intent = Intent()
//        intent.type = "image/*"
//        intent.action = Intent.ACTION_GET_CONTENT
//        startActivityForResult(intent, 2)
//    }
//
//    fun hasSdcard(): Boolean {
//        val state = Environment.getExternalStorageState()
//        return state == Environment.MEDIA_MOUNTED
//    }
//
//
//    internal var time: Long? = null
//    private fun doPhoto(requestCode: Int, data: Intent?) {
//        if (requestCode == 1) {
//            try {
//                picPath = UriUtils.getTakePhotoPath(data);
//                var impageUpload = ImageUploader();
//                impageUpload.ossImg(activity,picPath);
//            } catch (e: Exception) {
//                Log.e("EditClubActivity", e.message)
//            }
//
//        } else if (requestCode == 2) {
//            if (data == null) {
//                Toast.makeText(activity, "选择图片文件出错", Toast.LENGTH_LONG).show()
//                return
//            }
//            photoUri = data.data
//            if (photoUri == null) {
//                Toast.makeText(activity, "选择图片文件出错", Toast.LENGTH_LONG).show()
//                return
//            }
//            if (ContextCompat.checkSelfPermission(this.activity!!,
//                            Manifest.permission.WRITE_EXTERNAL_STORAGE) !== PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(this.activity!!,
//                        arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 2
//                )
//            } else {
//                picPath = UriUtils.getRealPathFromUriAboveApi19(activity, photoUri)
//            }
//
//            if (picPath != null && (picPath!!.endsWith(".png") || picPath!!.endsWith(".PNG") || picPath!!.endsWith(".jpg") || picPath!!.endsWith(".JPG"))) {
//                var impageUpload = ImageUploader();
//                impageUpload.ossImg(activity,picPath);
//            } else {
//                Toast.makeText(activity, "选择图片文件不正确", Toast.LENGTH_LONG).show()
//            }
//        }
//    }
//
//    override fun onRequestPermissionsResult(requestCode: Int, @NonNull permissions: Array<String>, @NonNull grantResults: IntArray) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        when (requestCode) {
//            1 -> {
//                //调用系统相机申请拍照权限回调
//                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    if (hasSdcard()) {
//                        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
//                            photoUri = Uri.fromFile(fileUri)
//                        } else {
//                            photoUri = FileProvider.getUriForFile(this.activity!!, this.activity!!.getPackageName() + ".provider", fileUri)
//                        }
//                        takephoto()
//                    } else {
//                        ToastUtil.toastLongMessage("设备没有SD卡！")
//                    }
//                } else {
//                    takephoto()
//                }
//            }
//            2//调用系统相册申请Sdcard权限回调
//            -> if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                pickPhoto()
//            } else {
//                ToastUtil.toastLongMessage("请允许操作SDCard！！")
//            }
//            PERMISSION_CAMERA_REQUEST_CODE -> {
//                if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                    //允许权限，有调起相机拍照。
//                    takePhone()
//                } else {
//                    //拒绝权限，弹出提示框。
//                    Toast.makeText(activity, "拍照权限被拒绝", Toast.LENGTH_LONG).show()
//                }
//            }
//        }
//    }
//
//    private fun takephoto() {
//        val intent = Intent()
//        intent.type = "image/*"
//        intent.action = Intent.ACTION_GET_CONTENT
//        startActivityForResult(intent, 2)
//    }
//
//
//    fun deleteImg(index:Int){
//        if(index>images.size-1){
//            return
//        }
//        images.removeAt(index);
//        setImages();
//    }
//    fun setImages(){
//        for (index in 0 until images.size){
//            if(index == 0) {
//                GlideEngine.loadImage(binding.imgO1, Uri.parse(images[0]))
//                binding.rlO1.visibility = View.VISIBLE
//            }
//            if(index == 1) {
//                GlideEngine.loadImage(binding.imgO2, Uri.parse(images[1]))
//                binding.rlO2.visibility = View.VISIBLE
//            }
//            if(index == 2) {
//                GlideEngine.loadImage(binding.imgO3, Uri.parse(images[2]))
//                binding.rlO3.visibility = View.VISIBLE
//            }
//        }
//        for (index in images.size until 3){
//            if(index == 0){
//                binding.rlO1.visibility = View.GONE
//            }
//            if(index == 1) {
//                binding.rlO2.visibility = View.GONE
//            }
//            if(index == 2) {
//                binding.rlO3.visibility = View.GONE
//            }
//        }
//        binding.imgAdd.visibility = if(images.size<3) View.VISIBLE else View.GONE
//
//        binding.viewModel?.cert_images = images
//    }
}
